package com.csz.servlet;

import com.csz.bean.Users;
import com.csz.service.UsersService;
import com.csz.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String userName = req.getParameter("TxtUserName");
        String password = req.getParameter("TxtPassword");

        //2.调取service层
        UsersService usersService = new UsersServiceImpl();
        Users users = usersService.login(userName, password);

        //3.跳转页面
        if (users==null){
            // 处理接受数据乱码，固定格式
            resp.setContentType("text/html;charset=utf-8");
            // 用弹窗的形式，告诉用户错误
            PrintWriter writer = resp.getWriter();
            String alert = "<script>location.href='login.jsp';alert('用户或密码不正确')</script>";
            writer.print(alert);
        }else {
            // 跳转到index页面 同时用session储存数据
            req.getSession().setAttribute("un",users);
            resp.sendRedirect("index.jsp");
        }
    }
}
